package b1.controls.basic
{
	import b1.conifg.*;
	import b1.net.*;
	import b1.utils.BFont;
	import b1.scenes.SceneContainer;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.filters.ColorMatrixFilter;
	import flash.filters.GlowFilter;
	import flash.filters.BitmapFilterQuality;
	import flash.text.*;
	import flash.utils.*;

	public class Clock extends Sprite
	{
		//一天的分类区间
		public static const seasonShortNames:Array = ["夜", "日"];
		public static const seasonNames:Array = ["黑夜", "白天"];
		//图片宽度
		private const imgWidth:int = 60;
		private var seasonName:TextField;
		private var mouseOverFlag:Boolean;
		private var clockSprite:Sprite;
		//提示剩余时间和阵营的强弱
		private var tip:BasicMessage;
		//四个区间的端点位置
		private const arrayX:Array = [BFont.stageWidth, 550, (BFont.stageWidth - imgWidth) / 2, 150, -imgWidth];
		private const arrayY:Array = [200, 70, 10, 70, 200];
		//用于改变白天和晚上背景的filter变化
		private const dayFilterAddArray:Array = [-15, 0, 5, 0, -15];
//		private const nightFilterAddArray:Array = [-30, -65, -70, -65, -30];
		private const nightFilterAddArray:Array = [-30, -65, -70, -65, -30];
		//用于改变太阳月亮图片的发光程度
		private const sunGlowFilterChangeArray:Array = [50, 200, 255, 200, 50];
		private const moonGlowFilterChangeArray:Array = [225, 235, 255, 235, 225];
		//上一次的season
		private var lastSeason:int;
		//加载图片的类（太阳和月亮）
		private var ClockImageSun:Class;
		private var ClockImageMoon:Class;
		//背景（用于改变亮度）
		private var spriteChangeFilter:Sprite;
		//改变亮度的背景
		private var filterChangeBackground:Sprite;
		
		public function Clock(skyBackground:Sprite, filterChangeBackground:Sprite)
		{
			super();
			this.spriteChangeFilter = skyBackground;
			this.filterChangeBackground = filterChangeBackground;
			mouseOverFlag = false;
			//加载当前显示图片
			ClockImageSun = ResourceHelper.getInstance().getClassByName("Sun");
			ClockImageMoon = ResourceHelper.getInstance().getClassByName("Moon");
			updateImgPosition();
			updateImg();
			updateFilter(spriteChangeFilter);	
			
			//Add season name
			seasonName = new TextField();
			seasonName.selectable = false;
        	seasonName.autoSize = TextFieldAutoSize.LEFT;
        	updateSeasonName();
//			addChild(seasonName);
			
			//Add timer
			var timer:Timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, onTick);
			timer.start();
			
			this.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);			
			this.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);			
		}
		
		public function onTick(event:TimerEvent):void
		{
			updateImgPosition();
			if (lastSeason != currentSeason)
			{
				updateImg();
				updateSeasonName();
			}
			if (mouseOverFlag)
				updateTip();
			updateFilter(spriteChangeFilter);	
		}
		
		//改变图片和背景的发光强弱
		private function updateFilter(spriteChangeFilter:Sprite):void
		{
			var remainSeconds:int = Config.secondsPerDay / 2 - ServerHelper.getInstance().now() % (Config.secondsPerDay / 2);
			var intevalSeconds:int = Config.secondsPerDay / 8;
			var currentInterval:int = 3 - int(remainSeconds / intevalSeconds);
			var currentIntervalRemainSeconds:int = remainSeconds % intevalSeconds;
			var matrixFilterAdd:Number;
			var golwFilter:GlowFilter;
			var glowFilterChange:Number;
			if (currentInterval >= 0)
			{
				if (currentSeason == 0)
				{
					glowFilterChange = sunGlowFilterChangeArray[currentInterval + 1] +  currentIntervalRemainSeconds * (sunGlowFilterChangeArray[currentInterval] - sunGlowFilterChangeArray[currentInterval + 1]) / intevalSeconds; 
					golwFilter = new GlowFilter(0xffff00 + int(glowFilterChange), 1, 4, 4, 2, BitmapFilterQuality.MEDIUM, false, false);
					
					matrixFilterAdd = this.dayFilterAddArray[currentInterval + 1] +  currentIntervalRemainSeconds * (this.dayFilterAddArray[currentInterval] - this.dayFilterAddArray[currentInterval + 1]) / intevalSeconds; 
				}
				else
				{
					glowFilterChange = moonGlowFilterChangeArray[currentInterval + 1] +  currentIntervalRemainSeconds * (moonGlowFilterChangeArray[currentInterval] - moonGlowFilterChangeArray[currentInterval + 1]) / intevalSeconds; 
					golwFilter = new GlowFilter(0xffff00 + int(glowFilterChange) + (0x1 << 8) * int(glowFilterChange) + (0x1 << 16) * int(glowFilterChange), 1, 4, 4, 2, BitmapFilterQuality.MEDIUM, false, false);

					matrixFilterAdd = this.nightFilterAddArray[currentInterval + 1] +  currentIntervalRemainSeconds * (this.nightFilterAddArray[currentInterval] - this.nightFilterAddArray[currentInterval + 1]) / intevalSeconds; 
				}
			}
			else
			{
				if (currentSeason == 0)
				{
					glowFilterChange = sunGlowFilterChangeArray[1] +  currentIntervalRemainSeconds * (sunGlowFilterChangeArray[0] - sunGlowFilterChangeArray[1]) / intevalSeconds; 
					golwFilter = new GlowFilter(0xffff00 + int(glowFilterChange), 1, 4, 4, 2, BitmapFilterQuality.MEDIUM, false, false);
					matrixFilterAdd = this.dayFilterAddArray[1] +  (intevalSeconds - 1) * (this.dayFilterAddArray[0] - this.dayFilterAddArray[1]) / intevalSeconds; 
				}
				else
				{
					glowFilterChange = moonGlowFilterChangeArray[1] +  currentIntervalRemainSeconds * (moonGlowFilterChangeArray[0] - moonGlowFilterChangeArray[1]) / intevalSeconds; 
					golwFilter = new GlowFilter(0xffff00 + int(glowFilterChange) + (0x1 << 8) * int(glowFilterChange) + (0x1 << 16) * int(glowFilterChange), 1, 4, 4, 2, BitmapFilterQuality.MEDIUM, false, false);
					matrixFilterAdd = this.dayFilterAddArray[1] +  (intevalSeconds - 1) * (this.dayFilterAddArray[0] - this.dayFilterAddArray[1]) / intevalSeconds; 
				}
			}
			golwFilter.strength = 10;
			this.clockSprite.filters = new Array(golwFilter);
			
			var matrixFilter:ColorMatrixFilter = new ColorMatrixFilter([1,0,0,0,int(matrixFilterAdd),
																      0,1,0,0,int(matrixFilterAdd),
																      0,0,1,0,int(matrixFilterAdd),
																      0,0,0,1,0 ]);
			spriteChangeFilter.filters = [matrixFilter];
			if (null != filterChangeBackground)
			{
//				filterChangeBackground.filters = [matrixFilter];
			}
		}

		//换图片（月亮、太阳）
		private function updateImg():void
		{
			if (null != clockSprite && null != clockSprite.parent)
			{
				clockSprite.parent.removeChild(clockSprite);
			}
			if (currentSeason == 0)
			{
				clockSprite = new ClockImageSun();
			}
			else
			{
				clockSprite = new ClockImageMoon();
			}
			lastSeason = currentSeason;
			clockSprite.width = imgWidth;
			clockSprite.scaleY = clockSprite.scaleX;
			addChild(clockSprite);
		}
		
		//改变图片的位置
		private function updateImgPosition():void
		{
			var remainSeconds:int = Config.secondsPerDay / 2 - ServerHelper.getInstance().now() % (Config.secondsPerDay / 2);
			var intevalSeconds:int = Config.secondsPerDay / 8;
			var currentInterval:int = 3 - int(remainSeconds / intevalSeconds);
			var currentIntervalRemainSeconds:int = remainSeconds % intevalSeconds;
			if (currentInterval >= 0)
			{
				this.x = this.arrayX[currentInterval + 1] +  currentIntervalRemainSeconds * (this.arrayX[currentInterval] - this.arrayX[currentInterval + 1]) / intevalSeconds; 
				this.y = this.arrayY[currentInterval + 1] +  currentIntervalRemainSeconds * (this.arrayY[currentInterval] - this.arrayY[currentInterval + 1]) / intevalSeconds; 
			}
			else
			{
				this.x = this.arrayX[1] +  (intevalSeconds - 1) * (this.arrayX[0] - this.arrayX[1]) / intevalSeconds; 
				this.y = this.arrayY[1] +  (intevalSeconds - 1) * (this.arrayY[0] - this.arrayY[1]) / intevalSeconds; 
			}
			
		}
		
		//改变图片显示的文字（日、夜）
		private function updateSeasonName():void
		{
			var textColor:int;
			//白天
			if (currentSeason == 0)
			{
				textColor = 0xFFFFFF;
			}
			//黑夜
			else
			{
				textColor = 0x000000;
			}
			seasonName.defaultTextFormat = new TextFormat("微软雅黑", 18, textColor, true);
			seasonName.text = seasonShortNames[currentSeason];
			seasonName.x = (clockSprite.width - seasonName.width) / 2;
			seasonName.y = (clockSprite.height - seasonName.height) / 2;
		}
		
		//改变说明的文字
		private function updateTip():void
		{
			if (tip != null && tip.parent != null)
			{
				tip.parent.removeChild(tip);
			}
        	var remainSeconds:int = Config.secondsPerDay / 2 - ServerHelper.getInstance().now() % (Config.secondsPerDay / 2);
        	var message:String = formatTimeToSecond(remainSeconds) + " 后 " + seasonNames[(currentSeason) % 2] + "\n";
			var messageAppend:String;
			if (currentSeason == 0)
			{
				messageAppend = "白天趣鸟阵营经验加成" + (Config.expBonusForDayNight * 100).toFixed(0) + "%";
			}
			else
			{
				messageAppend = "夜晚梦龙阵营经验加成" + (Config.expBonusForDayNight * 100).toFixed(0) + "%";
			}
			var tipWidth:int = Math.max(message.length, messageAppend.length);
			tip = new BasicMessage(18 * tipWidth, 50, message + messageAppend);
			tip.x = (this.width - tip.width) / 2 + this.x;
			tip.y = clockSprite.height + 10 + this.y;
			if (tip.x < 0)
			{
				tip.x = 0;
			}
			else if (tip.x + tip.width > BFont.stageWidth)
			{
				tip.x = BFont.stageWidth - tip.width;
			}
			SceneContainer.getInstance().currentScene.addChild(tip);
		}
		
		//得到当前是白天或者晚上
		public static function get currentSeason():int
		{
			return (ServerHelper.getInstance().now() % Config.secondsPerDay) / (Config.secondsPerDay / 2);
		}

		//规范显示时间: xx小时xx分钟xx秒
		public static function formatTimeToSecond(seconds:int):String
		{
        	var hours:int = seconds / 3600;
        	var minutes:int = seconds / 60 % 60;
        	var seconds:int = seconds % 60;
        	var timeStr:String = seconds + "秒";
        	if (minutes > 0)
        	{
        		timeStr = minutes + "分钟" + timeStr; 
        	}
        	if (hours > 0)
        	{
        		timeStr = hours + "小时" + timeStr;
        	}
        	return timeStr;
		}
		
		//规范显示时间: xx时xx分
		public static function setTimeDisplayFormatToMinute(seconds:int):String
		{
        	var hours:int = seconds / 3600;
        	var minutes:int = seconds / 60 % 60;
        	var seconds:int = seconds % 60;
        	var timeStr:String = "";
        	if (minutes > 0)
        	{
        		timeStr = minutes + "分"; 
        	}
        	if (hours > 0)
        	{
        		timeStr = hours + "时" + timeStr;
        	}
        	return timeStr;
		}
		
		private function onMouseOver(event:MouseEvent):void
        {
        	updateTip();
    		mouseOverFlag = true;
        }

		private function onMouseOut(event:MouseEvent):void
        {
        	if (tip != null && tip.parent != null)
        	{
        		tip.parent.removeChild(tip);
        		tip = null;
        	}
        	mouseOverFlag = false;
        }
	}
}